package cn.conac.as.monitor.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import cn.conac.as.framework.service.GenericService;
import cn.conac.as.framework.utils.StringUtils;
import cn.conac.as.framework.utils.TimestampUtils;
import cn.conac.as.monitor.entity.BdtVClientMonitorEntity;
import cn.conac.as.monitor.repository.BdtVClientMonitorRepository;
import cn.conac.as.monitor.vo.BdtVClientMonitorVo;

/**
 * 客户端监控视图的服务类
 * @author lishen
 * @date	2017年7月25日下午2:42:04
 * @version 1.0
 */
@Service
public class BdtVClientMonitorService extends GenericService<BdtVClientMonitorEntity, String> {

	@Autowired
	private BdtVClientMonitorRepository bdtVClientMonitorRepository;
	
	/**
	 * 根据id获取某一次客户端监控的详细信息
	 */
	public BdtVClientMonitorEntity findById(String id){
		return bdtVClientMonitorRepository.findOne(id);
	}

	/**
	 * 获取所有的BdtVClientMonitoryEntity对象
	 */
	public List<BdtVClientMonitorEntity> findAll(){
		return bdtVClientMonitorRepository.findAll();
	}
	
	/**
	 * 根据条件查找BdtClientMonitorEntity对象
	 * @return
	 */
	public List<BdtVClientMonitorEntity> findVClientMonitorByCondition(final BdtVClientMonitorVo bdtVClientMonitorVo){
		List<BdtVClientMonitorEntity> result = bdtVClientMonitorRepository.findAll(new Specification<BdtVClientMonitorEntity>() {
	        @Override
	        public Predicate toPredicate(Root<BdtVClientMonitorEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
	            List<Predicate> list = new ArrayList<Predicate>();

	            // 开始时间和结束时间
	            if (!StringUtils.isEmpty(bdtVClientMonitorVo.getBeginTime()) && !StringUtils.isEmpty(bdtVClientMonitorVo.getEndTime())) {
	                Timestamp beginTime=TimestampUtils.valueOf(bdtVClientMonitorVo.getBeginTime());
	                Timestamp endTime=TimestampUtils.valueOf(bdtVClientMonitorVo.getEndTime());
	                
	            	list.add(cb.between(root.get("exceptionErrorTime").as(Timestamp.class), beginTime, endTime));
	            }

	            Predicate[] p = new Predicate[list.size()];
	            return cb.and(list.toArray(p));
	        }

	    }, new Sort(Sort.Direction.DESC, "exceptionErrorTime")
		);

	    return result;
	}
}
